package com.hk.core.autoconfigure.authentication.security.servlet;

import com.alipay.api.AlipayClient;
import com.hk.alipay.security.AliPayAuthenticationProvider;
import com.hk.alipay.security.AliPayCallbackAuthenticationFilter;
import com.hk.core.authentication.api.UserPrincipal;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.util.function.Function;

/**
 * 支付宝认证配置
 *
 * @author Kevin
 * @date 2019/3/5 18:18
 */
@RequiredArgsConstructor
public class AliPayAuthenticationSecurityConfigurer extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    private final AlipayClient alipayClient;

    private final String processesUrl;

    private final String state;

    private final String scope;

    private final Function<String, UserPrincipal> authenticationFunction;

    @Override
    public void configure(HttpSecurity builder) {
        var filter = new AliPayCallbackAuthenticationFilter(processesUrl, alipayClient,
                state, scope);
        filter.setAuthenticationManager(builder.getSharedObject(AuthenticationManager.class));
        var provider = new AliPayAuthenticationProvider(authenticationFunction);
        builder.authenticationProvider(provider).addFilterAfter(filter, UsernamePasswordAuthenticationFilter.class);
    }
}
